<?php

namespace app\admin\controller\wdsxh;

use addons\wdsxh\library\Wxapp;
use app\admin\model\wdsxh\Order;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;
use \PhpOffice\PhpSpreadsheet\Spreadsheet;
use \PhpOffice\PhpSpreadsheet\IOFactory; //use \PHPExcel_Style_NumberFormat;    //设置列的格式==>>设置文本格式
/**
 * 入会申请
 *
 * @icon fa fa-circle-o
 */
class MemberProfile extends Backend
{

    /**
     * MemberProfile模型对象
     * @var \app\admin\model\wdsxh\MemberProfile
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wdsxh\MemberProfile;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->user;
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $this->view->assign("content", json_decode($row->content, true));
        $this->view->assign("user", $row->user);

        return $this->view->fetch();
    }

    public function pass($ids)
    {
        $row = $this->model->get($ids);
        if ($this->request->isPost()) {
            $fill_company = 0;
            $company_name = '';
            $content_array = json_decode($row['content'], true);
            foreach ($content_array as $k => $v) {
                if ($v['field'] == 'company') {
                    $company_name = $v['value'];
                }
            }
            $params = $this->request->post("row/a");
            $level = \app\admin\model\wdsxh\MemberUnitLevel::get($params['level_id']);
            if (!$level) {
                $this->error('会员级别信息错误');
            }
            if ($level['is_company'] == '1') {
                $fill_company = 1;
            }
            $expense = floatval($level->expense);
            $member = \app\admin\model\wdsxh\Member::where('uid', $row->uid)->find();
            if ($member) {
                $member->uid = $row->uid;
                $member['name'] = $row['name'];
                $member->mobile = $row->mobile;
                $member->level_id = $params['level_id'];
                $member->jointime = $expense > 0 ? date('Y-m-d') : $level['jointime'];
                $member->expiretime = $expense > 0 ? date('Y-m-d') : $level['expiretime'];
                $member->status = 1;
                $res = $member->save();
            } else {
                $data = array(
                    'uid' => $row->uid,
                    'name' => $row['name'],
                    'mobile' => $row->mobile,
                    'picture' => '/assets/addons/wdsxh/img/default.png',
                    'level_id' => $params['level_id'],
                    'jointime' => $expense > 0 ? date('Y-m-d') : $level['jointime'],
                    'expiretime' => $expense > 0 ? date('Y-m-d') : $level['expiretime'],
                    'status' => '1',
                );
                $res = \app\admin\model\wdsxh\Member::create($data);
            }
            $memberUnitLevelObj = (new \app\admin\model\wdsxh\MemberUnitLevel())->get($params['level_id']);
            if ($res) {
                $row->status = '1';
                $row->save();
                if ($res->status == '1' || ($expense > 0)) {
                    $Coceral = wdsxh_get_coceral();
                    if ($memberUnitLevelObj['expense'] == 0.00) {
                        $money = (new \app\admin\model\wdsxh\MemberUnitLevel())->where('id', $params['level_id'])->value('expense');
                        $orderData = array(
                            'uid' => $row->uid,
                            'items_id' => $res->id,
                            'type' => 2,
                            'order_sn' => wdsxh_create_order(),
                            'money' => $money,
                            'status' => '2',
                            'createtime' => time(),
                            'paytime' => time(),
                        );
                        Order::create($orderData);
                        $thing1_value = '恭喜您，您已成功加入' . $Coceral['name'];
                        $path = '/pages/Personal/index';
                    } else {
                        $thing1_value = '通过审核，请前往小程序缴纳会费！';
                        $path = '/pages/Component/Module/Payment/Program/pay/index/index';
                    }
                    //入会申请成功通知
                    $Coceral = wdsxh_get_coceral();
                    try {
                        $conf = (new \app\admin\model\wdsxh\Config())->where('id', 1)->find();
                        $data = [
                            'thing3' => [
                                'value' => $Coceral['name'],
                            ],
                            'time2' => [
                                'value' => date('Y-m-d H:i:s'),
                            ],
                            'thing1' => [
                                'value' => $thing1_value,
                            ]
                        ];
                        $result = Wxapp::subscribeMessage($conf['initiation_success'], trim(wdsxh_get_openid($row->uid)), $path, $data);
                    } catch (\think\Exception $e) {
                        $this->error($e->getMessage());
                    }
                }
                if ($memberUnitLevelObj['expense'] == 0.00) {
                    //入会审核成功通知
                    try {
                        $conf = (new \app\admin\model\wdsxh\Config())->where('id', 1)->find();
                        $data = [
                            'thing1' => [
                                'value' => $row['name'],
                            ],
                            'time3' => [
                                'value' => date('Y-m-d H:i:s'),
                            ],
                            'phrase4' => [
                                'value' => '审核通过',
                            ],
                            'thing5' => [
                                'value' => '恭喜成功加入会员',
                            ],
                        ];
                        $result = Wxapp::subscribeMessage($conf['initiation_audit'], trim(wdsxh_get_openid($row->uid)), '/pages/Personal/index', $data);
                    } catch (\think\Exception $e) {
                        $this->error($e->getMessage());
                    }
                }

                if ($fill_company && ($memberUnitLevelObj['expense'] == 0.00)) {
                    $member_unit_data = array(
                        'level_id' => $params['level_id'],
                        'member_id' => $res->id,
                        'company_name' => $company_name,
                        'status' => '0',
                        'cat_id' => '',
                        'company_principal' => '',
                        'createtime' => time(),
                    );
                    \app\admin\model\wdsxh\MemberUnit::create($member_unit_data);
                }
                $business = [
                    'uid' => $res->id,
                    'status' => '1',
                ];
                $user_id = $row->uid;
                \app\admin\model\wdsxh\Business::where('user_id', $user_id)->update($business);
                $this->success('操作成功！');
            }
            $this->error('发生未知错误');
        }
        return $this->view->fetch();
    }

    public function refuse($ids)
    {
        $row = $this->model->get($ids);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $row->reason = $params['reason'];
            $row->status = '2';
            $row->save();

            //入会审核成功通知
            try {
                $conf = (new \app\admin\model\wdsxh\Config())->where('id', 1)->find();
                $data = [
                    'thing1' => [
                        'value' => $row['name'],
                    ],
                    'time3' => [
                        'value' => date('Y-m-d H:i:s'),
                    ],
                    'phrase4' => [
                        'value' => '审核未通过',
                    ],
                    'thing5' => [
                        'value' => '原因：' . $params['reason'],
                    ],
                ];
                Wxapp::subscribeMessage($conf['initiation_audit'], trim(wdsxh_get_openid($row->uid)), '/pages/Component/Module/Main/Program/apply/index/index', $data);
            } catch (\think\Exception $e) {
            }

            $this->success();
        }
        return $this->view->fetch();
    }

    public function action($state = 0, $ids = '')
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row->status = $state ? '1' : '2';
        try {
            if ($state == 1) {
                $member = \app\admin\model\wdsxh\Member::where('uid', $row->uid)->find();
                if ($member) {
                    throw new Exception('该用户已经是会员了！');
                }
                $data = array(
                    'uid' => $row->uid,
                    'name' => $row['name'],
                    'mobile' => $row->mobile,
                    'level_id' => $this->getMemberMinLevel(),
                    'jointime' => date('Y-m-d'),
                    'expiretime' => date('Y-m-d'),
                );
                \app\admin\model\wdsxh\Member::create($data);
            }
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $row->save();
        $this->success('操作成功！');
    }

    private function getMemberMinLevel()
    {
        $level = \app\admin\model\wdsxh\MemberUnitLevel::order('weigh desc')->field('id')->find();
        return $level['id'];
    }

    public function fieldset()
    {
        if ($this->request->isPost()) {
            $params = $this->request->param('row/a');
            if (empty($params['field']) || !is_array($params['field'])) {
                $this->error('字段信息不能为空');
            }
            $temp = array();
            foreach ($params['field'] as $row) {
                $temp[] = $row;
            }
            $field_array = array_column($temp, 'field');
            if (count($field_array) != count(array_unique($field_array))) {
                $this->error('字段名不能重复');
            }
            config('fieldset', $temp);
            file_put_contents(
                ADDON_PATH . "wdsxh" . DS . 'config' . DS . "fieldset.php",
                '<?php' . "\n\nreturn " . var_export_short($temp) . ";\n"
            );
            $this->success('操作成功！');
        }
        $config_file = ADDON_PATH . "wdsxh" . DS . 'config' . DS . "fieldset.php";
        if (is_file($config_file)) {
            $fidldset = include $config_file;
        }
        if (empty($fidldset)) {
            $fidldset = array(
                0 =>
                    array(
                        'type' => 'text',
                        'label' => '真实姓名',
                        'field' => 'name',
                        'option' => '请输入你的真实姓名',
                    ),
                1 =>
                    array(
                        'type' => 'number',
                        'label' => '联系电话',
                        'field' => 'mobile',
                        'option' => '请输入你的联系电话',
                    ),
                2 =>
                    array(
                        'type' => 'radio',
                        'label' => '性别',
                        'field' => 'gender',
                        'option' => '男,女',
                    ),
            );
        }
        $this->assign('fieldset', json_encode($fidldset));
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            $param['status'] = '3';
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                    \app\admin\model\wdsxh\Member::where('uid', $v->uid)->delete();
                    \app\admin\model\wdsxh\Business::where('user_id', $v->uid)->update($param);
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


    /**
     * 导出
     */
    public function export($ids = "")
    {
        if ($this->request->isPost()) {
            set_time_limit(0);
            ini_set('memory_limit', '2048M');
            $search = $this->request->post('search');
            $ids = $ids ? $ids : $this->request->post("ids");
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $op = $this->request->post('op');

            $this->request->get(['search' => $search, 'ids' => $ids,'op' => $op]);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if ($ids == 'all'){
                $sql = $this->model
                    ->where($where)
                    ->where('content','not in','Null')
                    ->field('content')
                    ->select();
            }else{
                $sql = $this->model
                    ->where($pk, 'in', $ids)
                    ->where($where)
                    ->where('content','not in','Null')
                    ->field('content')
                    ->select();
            }
//            $sql = $this->model
//                ->where($pk, 'in', $ids)
//                ->where($where)
//                ->where('content','not in','Null')
//                ->field('content')
//                ->select();
            $sql = collection($sql)->toArray();

            foreach ($sql as $k=>$v){
                if ($v['content']){
                    $sql[$k]['content'] = json_decode($v['content'],true);
                }

            }
            //  p($sql);
            $newExcel = new Spreadsheet();  //创建一个新的excel文档
            $objSheet = $newExcel->getActiveSheet();  //获取当前操作sheet的对象
            $objSheet->setTitle('入会申请');  //设置当前sheet的标题

            $newExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
            $newExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
            $newExcel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
            $newExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
            $newExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
            $newExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
            $newExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
            $newExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
            $newExcel->getActiveSheet()->getColumnDimension('I')->setWidth(20);
            $newExcel->getActiveSheet()->getColumnDimension('J')->setWidth(20);
            $newExcel->getActiveSheet()->getColumnDimension('K')->setWidth(20);
            $newExcel->getActiveSheet()->getColumnDimension('L')->setWidth(20);
            $newExcel->getActiveSheet()->getColumnDimension('M')->setWidth(20);
            $newExcel->getActiveSheet()->getColumnDimension('N')->setWidth(20);
            $newExcel->getActiveSheet()->getColumnDimension('O')->setWidth(20);
            $newExcel->getActiveSheet()->getColumnDimension('p')->setWidth(20);
            $newExcel->getActiveSheet()->getColumnDimension('q')->setWidth(20);
            $newExcel->getActiveSheet()->getColumnDimension('r')->setWidth(20);
            $newExcel->getActiveSheet()->getColumnDimension('s')->setWidth(20);
            $newExcel->getActiveSheet()->getColumnDimension('T')->setWidth(20);
            $labels = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'p', 'q', 'r', 's', 'T'); // 列标的数组
            // 外部循环遍历 $sql 数组
            foreach ($sql as $rowIndex => $row) {
                // 设置每一行的标签（label）
                for ($i = 0; $i < count($row['content']); $i++) {
                    $label = isset($row['content'][$i]['label']) ? $row['content'][$i]['label'] : '';
                    $objSheet->setCellValue($labels[$i] . '1', $label);
                }

                // 内部循环遍历 content 数组，设置每一行的值
                for ($j = 0; $j < count($row['content']); $j++) {
                    $value = isset($row['content'][$j]['value']) ? $row['content'][$j]['value'] : '';
                    $objSheet->setCellValue($labels[$j] . ($rowIndex + 2), $value);
                }
            }
            /*--------------下面是设置其他信息------------------*/
            $title = date("Ymd-入会申请");
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $title . '.xlsx"');
            header('Cache-Control: max-age=0');
            $objWriter = IOFactory::createWriter($newExcel, 'Xlsx');
            $objWriter->save('php://output');
            return;

        }
    }
}
